package it.uniroma2.structure;

import java.io.Serializable;
import java.util.Vector;

public class Assign implements BPEL_Element, Serializable{
	private boolean validate;
	private String name;
	private static int index = 1;
	private static String defaultName = "Assign";
	private Vector<Copy> copies;
	
	
	public Assign(){
		this.validate = false;
		this.copies = new Vector<Copy>();
		this.name = defaultName + index;
		index++;
	}
	
	
	public Assign(String name){
		this.validate = false;
		this.copies = new Vector<Copy>();
		this.name = name;
	}
	
	
	public Assign(Parameter from, Parameter to) {
		this();
		Copy copy = new CopyParameter(from, to);
		this.copies.addElement(copy);
	}
	
	
	public Assign(String name, Parameter from, Parameter to) {
		this(name);
		Copy copy = new CopyParameter(from, to);
		this.copies.addElement(copy);
	}
	
	
	public void addNewCopy(Parameter from, Parameter to){
		Copy newCopy = new CopyParameter(from, to);
		if(this.copies.size() == 0){
			Variable var = to.getVariable();
			if(var instanceof VariableService){
				String msg = ((VariableService)var).getMessageType();
				Service service = ((VariableService)var).getService();
				String expr = service.getHierarchyElement(msg, "impl");
//				System.out.println(expr);
				Literal literal = new Literal(expr, true);
				CopyLiteral instanceVar = new CopyLiteral(literal, var);
				this.copies.add(instanceVar);
			}else if(var instanceof VariableProcess){
				String expr = ((VariableProcess)var).getHierarchyProcessWSDL();
				Literal literal = new Literal(expr, true);
				CopyLiteral instanceVar = new CopyLiteral(literal, var);
				this.copies.add(instanceVar);
			}
		}
		this.addNewCopy(newCopy);
	}
	
	
	public void removeCopy(Copy copy){
		for(Copy tempCopy : this.copies){
			if(tempCopy.equals(copy)){
				copies.remove(tempCopy);
			}
		}
	}
	
	
	public void addNewCopy(Copy newCopy){
		this.copies.addElement(newCopy);
	}
	
	
	@Override
	public String toBPEL() {
		String output = "";
		if(this.validate){
			output = output + "<" + assignTag + " validate=\"yes\" name=\"" + this.name + "\">\n";
		}else{
			output = output + "<" + assignTag + " validate=\"no\" name=\"" + this.name + "\">\n";
		}
		
		for(Copy tempCopy : this.copies){
			output = output + tempCopy.toBPEL();
		}
		output = output + "</" + assignTag + ">\n";
		return output;
	}


	public Vector<Copy> getCopies() {
		return copies;
	}


	public void setCopies(Vector<Copy> copies) {
		this.copies = copies;
	}
}
